package edu.ynu.hhy.architectureclass.dao;

import edu.ynu.hhy.architectureclass.entity.TokenResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class TokenDao {
    private static final Logger logger = LoggerFactory.getLogger(TokenDao.class);

    @Value("${fbox.token.url}") // FBox 获取 token 的 URL
    private String fboxTokenUrl;

    @Value("${fbox.client.id}") // FBox 客户端 ID
    private String fboxClientId;

    @Value("${fbox.client.secret}") // FBox 客户端密钥
    private String fboxClientSecret;

    @Value("${ys.api.url}") // 萤石 API 的 URL
    private String ysApiUrl;

    @Value("${ys.account.id}") // 萤石子账户 ID
    private String ysAccountId;

    @Autowired
    private RestTemplate restTemplate;

    public String getFBoxToken() {
        // 构造请求体
        String requestBody = "scope=fbox" +
                "&client_id=" + fboxClientId +
                "&client_secret=" + fboxClientSecret +
                "&grant_type=client_credentials";

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 构造请求实体
        HttpEntity<String> request = new HttpEntity<>(requestBody, headers);

        // 发送 POST 请求
        try {
            ResponseEntity<Map> response = restTemplate.postForEntity(fboxTokenUrl, request, Map.class);
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                Map<String, Object> responseBody = response.getBody();
                return (String) responseBody.get("access_token"); // 返回 access_token
            }
        } catch (Exception e) {
            System.err.println("Failed to fetch FBox access token: " + e.getMessage());
            e.printStackTrace();
        }

        return null;
    }
    /**
     * 获取萤石 API 的访问令牌
     *
     * @return 访问令牌
     */
    public String getYsToken() {
        // 构造请求体
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("accountId", ysAccountId);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 构造请求实体
        HttpEntity<Map<String, String>> request = new HttpEntity<>(requestBody, headers);

        // 发送 POST 请求
        try {
            ResponseEntity<Map> response = restTemplate.postForEntity(ysApiUrl, request, Map.class);
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                Map<String, Object> responseBody = response.getBody();
                if (responseBody.containsKey("data")) {
                    Map<String, Object> data = (Map<String, Object>) responseBody.get("data");
                    return (String) data.get("accessToken"); // 返回 accessToken
                } else {
                    System.err.println("API 响应中缺少 'data' 字段");
                }
            } else {
                System.err.println("API 调用失败，状态码: " + response.getStatusCode());
                System.err.println("响应内容: " + response.getBody());
            }
        } catch (Exception e) {
            System.err.println("Failed to fetch Ys access token: " + e.getMessage());
            e.printStackTrace();
        }

        return null;
    }
}
